import store from 'store';
import { Toast } from 'vant';
import moment from 'moment';

export default {
	state: {
		list: []
	},

	actions: {
		getTaskList({ commit }) {
			this.service.bwbt.goldTask
				.list()
				.then(res => {
					console.log('任务列表', res);
					commit('SET_TASKLIST', res);
				})
				.catch(err => {
					Toast(err.message);
				});
		},

		finishTask({ state, dispatch, commit }, { sceneKey, category }) {
			return new Promise((resolve, reject) => {
				let item = null;

				if (category) {
					item = state.list.find(e => e.floorId == category);
				}

				if (sceneKey) {
					item = state.list.find(e => e.sceneKey == sceneKey);
				}

				if (!item || !item.sceneKey) {
					return reject('sceneKey 不存在');
				}

				console.log(`任务【${item.sceneKey}】`, !!item);

				if (item && item.sceneKey) {
					const date = store.get(`task-${item.sceneKey}`);

					if (!date || moment(date).isBefore(moment().format('YYYY-MM-DD 00:00:00'))) {
						this.service.bwbt.bwbtGold
							.receive({
								sceneKey: item.sceneKey,
								scene: 2
							})
							.then(res => {
								store.set(`task-${item.sceneKey}`, moment().format('YYYY-MM-DD HH:mm:ss'));

								console.log(`任务【${item.sceneKey}】执行成功`);

								Toast(`您完成了任务，金币+${res}`);

								// 更新用户信息
								dispatch('GET_BWBT_USERINFO');

								// 完成任务
								commit('FINISH_TASK', { sceneKey: item.sceneKey });

								resolve(res);
							})
							.catch(err => {
								console.warn(`任务【${item.sceneKey}】执行异常`, err.message);
								reject(err.message);
							});
					} else {
						console.warn(`任务【${item.sceneKey}】今日已执行`);
						reject('今日已执行');
					}
				} else {
					reject('sceneKey 不存在');
				}
			});
		},

		isNewTask({}, sceneKey) {
			const date = store.get(`task-${sceneKey}`);
			return date ? moment(date).isBefore(moment().format('YYYY-MM-DD 00:00:00')) : true;
		}
	},

	mutations: {
		SET_TASKLIST(state, list) {
			state.list = list;
		},
		FINISH_TASK(state, { sceneKey }) {
			state.list.map(e => {
				if (e.sceneKey == sceneKey) {
					e.receiveStatus = 1;
				}
			});
		}
	}
};
